<?php
App::uses('AppController', 'Controller');
App::uses('AppUtility','Lib');
class UsersController extends AppController {
	public $name = 'Users';
	public $helpers = array('Html', 'Form','Paginator');
	public $components = array('Paginator');
	public $uses = array('Users');
	
		public function beforeFilter() {
			parent::beforeFilter();
			$this->layout = 'admin';
		}
	/**
	 * login user by Auth
	 * @author: hangbtt
	 */
	public function login() {
        $userLogin = $this->Auth->user();
        if(!empty($userLogin) && $userLogin['group_id'] == 1){
           $this->redirect('/Users/userManager');
           return false;
        }
		if ($this->request->is('post')) {
			$this->request->data['type'] = AppConst::LOGIN_ADMIN;
			if ($this->Auth->login()) {				
				$this->redirect('/Users/userManager');
			} else {
				$this->Session->setFlash("<div class='invalid-msg'>Your username or password was incorrect.</div>");
            }
		}
		$this->layout='login';		
	}
    public function loginFontEnd(){
        if ($this->request->is('post')) {
			$this->request->data['type'] = AppConst::LOGIN_FONT_END;
			if ($this->Auth->login()) {	
                $userLogin = $this->Auth->user();
                if(!empty($userLogin) && $userLogin['group_id'] == 1){
                    $this->Auth->logout();
                    $this->Session->setFlash("<div class='invalid-msg'>Your username or password was incorrect.</div>");
                }else{
                    $this->Users->save(array('Users' => array('id' => $userLogin['id'],'stats_online' => 1)));
				    $this->redirect('/Home/index');
                }
			} else {
				$this->Session->setFlash("<div class='invalid-msg'>Your username or password was incorrect.</div>");
            }
		}
        $this->redirect('/Home/index');
        $this->layout='login';
    }
	/**
	 * Clear cookie and redirect to url which define in AppController's logoutRedirect
	 */
	public function logout() {
		$this->Session->setFlash('');
		$this->redirect($this->Auth->logout());
	}
    public function logout_font_end() {
		$this->Session->setFlash('');
        $userLogin = $this->Auth->user();
        $this->Users->save(array('Users' => array('id' => $userLogin['id'],'stats_online' => 0)));
        $this->Auth->logoutRedirect = '/Home';
		$this->redirect($this->Auth->logout());
	}
    
	/**
	 * index method
	 *
	 * @return void
	 */
	public function index() {
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}
	public function sitemap() {

	}

	/**
	 * view user method
	 *
	 * @param string $id
	 * @return void
	 */
	public function view($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->set('user', $this->User->read(null, $id));
	}

	/**
	 * add user method
	 *
	 * @return void
	 */
	public function add($data = null) {
		if ($data){
			$this->User->create();
			if ($this->User->save($data) ){
				return true;
			} else {
				return false;
			}
		} elseif ($this->request->is('post')) {
			$this->User->create();
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		}
		$groups = $this->User->Group->find('list');
		$this->set(compact('groups'));
	}

	/**
	 * edit user method
	 *
	 * @param string $id
	 * @return void
	 */
	public function edit($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}

		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		} else {
			$this->request->data = $this->User->read(null, $id);
		}
		$groups = $this->User->Group->find('list');
		$this->set(compact('groups'));
	}

	/**
	 * delete user method
	 *
	 * @param string $id
	 * @return void
	 */
	public function delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this->User->delete()) {
			$this->Session->setFlash(__('User deleted'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('User was not deleted'));
		$this->redirect(array('action' => 'index'));
	}
	/**
	 * Function userManager
	 * @author MinhPhan
	 * 
	 */
	public function userManager(){
		if(isset($this->request->query['uid'])){
			$this->Users->delete($this->request->query['uid']);
		}
// 		$this->paginate = array(                
//     				'fields'        => '*',
//     				'limit'         => 2
// 					);
		$arrResult = $this->paginate('Users');
		if (isset($this->request->query['user'])) {
			$username = $this->request->query['user'];
			$arrUser = $this->Users->find('all',array('conditions'=>array(
					'username LIKE'=>'%'.$username.'%'
			)));
			$Usernumber = count($arrUser);
			$dataview = $this->zendHTML($arrUser);
		}else{
			$Usernumber = count($arrResult);
			$dataview = $this->zendHTML($arrResult);
		}
		$this->set('arrUser',$arrResult);
		$this->set('usernumber',$Usernumber); 
		$this->set('dataview',$dataview);
		$this->layout = 'admin';
		
	}
	/**
	 * Function ZendHTML
	 * @author Minh Phan
	 * @param unknown $arrUser
	 * @return string
	 */
	public function zendHTML($arrUser){
			if($arrUser){
				foreach ($arrUser as $userInfo){
					if($userInfo['Users']['group_id'] == 0){
						$grounp = 'Admin';
					}else{
						$grounp ='User';
					}
					$dataView[]=	"<tbody>
										<tr class='odd'>
											<td>". $userInfo['Users']['id']."</td>
											<td ><img src='".$userInfo['Users']['avata']."' alt='' /></td>
											<td class ='username'>". $userInfo['Users']['username']."</td>
											<td>".$userInfo['Users']['email']."</td>
											<td>".AppUtility::ConvertTimeToDay($userInfo['Users']['brithday'])."</td>
											<td>". $userInfo['Users']['total_money']."</td>
											<td>". AppUtility::ConvertTimeToDay($userInfo['Users']['create_time'])."</td>
											<td>".$grounp."</td>
											<td>
													<li><a role='menuitem' tabindex='-1' href='javascript:;' uid =".$userInfo['Users']['id']." class='deleteUser' title='Remove formatting'>Delete User</a></li>	
											</td>
										</tr>
										
									</tbody>
									";
					}
					return $dataView;
			}
			}
	function info(){
		$username = $this->request->data['username'];
		if($username){
			$arrResult = $this->Users->find('first',array('conditions'=>array(
									'username'=>$username
								)));
			$arrDataReturn = json_encode($arrResult);
			$this->response->body($arrDataReturn);
			return $this->response;
		}
	}
	
	function update(){
			$arrData = $this->request->data;
			$arrUpdate[] = $arrData;
			debug($arrUpdate);
			$this->Users->updateMutil($arrUpdate);
			$arrDataReturn = json_encode($arrUpdate);
			$this->response->body($arrDataReturn);
			return $this->response;
		}
		
	function testLogin(){
		$this->layout='login';
		
	}
	function testRegister(){
		$this->layout='login';
	}
			
}
